import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:english_words/english_words.dart';
import 'package:testchat/chat_members/chat_c.dart';
import '../chat_members/chat_a.dart';
import '../chat_members/chat_b.dart';

class ChatPage extends StatefulWidget {
  const ChatPage({super.key});
  @override
  _ChatPageState createState() => _ChatPageState();
}

int randomGen(max) {
  var x = Random().nextInt(max);
  return x.floor();
}

String generateRandomString() {
  final length = randomGen(100);
  final _random = Random();
  const seedChars = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890";
  final randomString = List.generate(length, (index) => seedChars[_random.nextInt(seedChars.length)]).join();
  return randomString;
}
class _ChatPageState extends State<ChatPage> {
  static const loadingTag = "##loading##";
  var _words = <String>[loadingTag];

  @override
  void initState() {
    super.initState();
    _retrieveData();
  }

  @override
  Widget build(BuildContext context) {
    return ListView.separated(
      itemCount: _words.length,
      itemBuilder: (context, index) {
        //如果到了表尾
        if (_words[index] == loadingTag) {
          //不足10000条，继续获取数据
          if (_words.length - 1 < 10000) {
            //获取数据
            _retrieveData();
            //加载时显示loading
            return Container(
              padding: const EdgeInsets.all(16.0),
              alignment: Alignment.center,
              child: SizedBox(
                width: 24.0,
                height: 24.0,
                child: CircularProgressIndicator(strokeWidth: 2.0),
              ),
            );
          } else {
            //已经加载了10000条数据，不再获取数据。
            return Container(
              alignment: Alignment.center,
              padding: EdgeInsets.all(16.0),
              child: Text(
                "没有更多了",
                style: TextStyle(color: Colors.grey),
              ),
            );
          }
        }
        //显示单词列表项
        // return ListTile(title: Text(_words[index]));
        return ListTile(title: index % 5 == 0 ? ChatC(id: index) : (index % 2 == 0 ? ChatA(text: "$index : ${_words[index]} : ${generateRandomString()}") : ChatB(text:"$index : ${_words[index]} : ${generateRandomString()}")));
      },
      separatorBuilder: (context, index) => Divider(height: .0, color: Color.fromARGB(255, 255, 255, 255),),
    );
  }

  void _retrieveData() {
    Future.delayed(Duration(seconds: 1)).then((e) {
      // List<String> infoList = getInfoList() as List<String>;
      setState(() {
        //重新构建列表
        _words.insertAll(
          _words.length - 1,
          // infoList,
          generateWordPairs().take(1000).map((e) => e.asPascalCase).toList(),
        );
      });
    });
  }
}